#coding=utf-8
#人脸识别类 - 使用face_recognition模块,识别完成后，显示名字，并保存照片
import cv2
import face_recognition
import os
import numpy
import win32gui
import win32con
import datetime
#预定义好的人的照片放到下面的路径，图片最好非常小，小于50k，且以人物的拼音命名
path = "img/face_recognition"  # 模型数据图片目录

total_image_name = []
total_face_encoding = []

#提取预定义人脸特征
for fn in os.listdir(path):  #fn 表示的是文件名q

    total_face_encoding.append(
        face_recognition.face_encodings(
            face_recognition.load_image_file(path + "/" + fn))[0])
    fn = fn[:(len(fn) - 4)]  #截取图片名（这里应该把images文件中的图片名命名为为人物名）
    total_image_name.append(fn)  #图片名字列表

#自定义人脸识别函数，打开摄像头，并做人脸匹配
def face():
    cv2.namedWindow("capture")
    win32gui.SetForegroundWindow(win32gui.FindWindow(None,"capture"))
    win32gui.ShowWindow(win32gui.FindWindow(None,"capture"), win32con.SW_SHOW)
    cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)

    cap.set(3,320)
    cap.set(4,180)
    while (1):

        ret, frame = cap.read()
        frame=cv2.resize(frame,(160,90))

        # 发现在视频帧所有的脸和face_enqcodings
        face_locations = face_recognition.face_locations(frame)
        face_encodings = face_recognition.face_encodings(frame, face_locations)
        # 在这个视频帧中循环遍历每个人脸
        for (top, right, bottom, left), face_encoding in zip(
                face_locations, face_encodings):
            # 看看面部是否与已知人脸相匹配。
            for i, v in enumerate(total_face_encoding):
                match = face_recognition.compare_faces(
                    [v], face_encoding, tolerance=0.4)
                name = "Unknown"
                if match[0]:
                    name = total_image_name[i]
                    print(name)
                    filename=datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S')
                    #保存照片
                    cv2.imwrite(filename+'.jpg',frame)
                    cap.release()
                    cv2.destroyAllWindows()
                    return name
                    #break
            # 画出一个框，框住脸
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
            # 画出一个带名字的标签，放在框下
            #cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255),cv2.FILLED)
            font = cv2.FONT_HERSHEY_DUPLEX
            cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.2,(255, 255, 255), 1)
        # 显示结果图像
        cv2.imshow('capture', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
if __name__ == "__main__":
    face()


